import React from 'react';
import {App, Button, Form, Space, Spin} from "antd";
import {AsyncThunk} from "@reduxjs/toolkit";
import {AsyncThunkConfig} from "@reduxjs/toolkit/src/createAsyncThunk";
import {useAppDispatch} from "../../redux/hook";
import LogFactory from "../../log/LogFactory";
import {FormInstance} from "antd/lib";
import {useNavigate} from "react-router-dom";


interface FormEnhanceProps<T> {
    /**
     * 添加数据的redux异步action 
     */
    fetchAddData: AsyncThunk<number,any, AsyncThunkConfig> ,
    /**
     * 表单数据的初始值
     */
    initialValues?: Partial<T> ,
    /**
     * 表单的子组件
     */
    children?: React.ReactNode,
    /**
     * 表单的实例
     */
    form?: FormInstance<T>,
    /**
     * 提交按钮的文本
     */
    submitText?: string,
}

const log = LogFactory.getLog("FormEnhance") ;

const FormEnhance = <T,> (props: FormEnhanceProps<T>) => {

    const { form } = props ;
    const [loading, setLoading] = React.useState<boolean>(false) ;
    // const [form] = Form.useForm<T>() ;
    const { message } = App.useApp() ;
    const dispatch = useAppDispatch() ;
    const navigate = useNavigate() ;

    const onFinish = async (value: T) => {
        log.debug("表单提交的数据: " , value) ;
        setLoading(true) ;
        const res = await dispatch(props.fetchAddData(value)).unwrap().then(res => res) ;
        setLoading(false) ;
        if (res > 0){
                message.success("添加成功") ;
                navigate("../") ;
        }else {
            message.info("添加失败") ;
        }
    } ;

    const onReset = () => {
        form?.resetFields() ;
    };
    
    return (
        <Spin
            spinning={loading}
            tip={"正在提交数据..."}
            delay={500}
        >
            <Form<T>
                layout={"horizontal"}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 12 }}
                form={form}
                initialValues={props.initialValues}
                onFinish={onFinish}
            >

                {props.children}
                <Form.Item wrapperCol={{offset: 8,span: 16}}>
                    <Space size={10}>
                        <Button type="primary" htmlType="submit">{props.submitText || "提交" }</Button>
                        <Button type="default" htmlType="reset" onReset={onReset}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Spin>
    );
};

export default FormEnhance;